package com.cai.btautolink

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothClass
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.hardware.input.InputManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.cai.btautolink.AutoConfirmAccessibilityService.ACT_CLOSE_AUTO
import com.cai.btautolink.MyService.Companion


class MainActivity : AppCompatActivity() {

    companion object {
        const val TAG = "MainActivity"
        const val WHAT_BLUETOOTH_START_SCAN = 1
        const val WHAT_BLUETOOTH_BOND = 2

        const val permissionRequestCode = 1
        val permissions = arrayOf(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
    }

    private val bluetoothStateReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent!!.action

            // 监听蓝牙状态变化的广播
            if (BluetoothAdapter.ACTION_STATE_CHANGED == action) {
                // 从广播中获取当前蓝牙状态
                val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
                when (state) {
                    BluetoothAdapter.STATE_OFF -> {
                        Log.d(TAG, "蓝牙已关闭")
                    }
                    BluetoothAdapter.STATE_ON -> {
                        Log.d(TAG, "蓝牙已开启")

                        startDiscovery()
                    }
                    BluetoothAdapter.STATE_TURNING_ON -> {
                        Log.d(TAG, "蓝牙正在开启...")
                    }
                    BluetoothAdapter.STATE_TURNING_OFF -> {
                        Log.d(TAG, "蓝牙正在关闭...")
                    }
                    else -> {
                        Log.d(TAG, "未知蓝牙状态")
                    }
                }

            }
        }
    }

    private val bluetoothScanReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent!!.action

            // 监听蓝牙扫描结果广播
            if (BluetoothDevice.ACTION_FOUND == action) {
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
//                Log.d(TAG, "扫描到设备：${device}")
                if (device != null) {

                    val majorDeviceClass = device.bluetoothClass.majorDeviceClass
                    when (majorDeviceClass) {
                        BluetoothClass.Device.Major.PHONE -> {
                            Log.d(TAG, "扫描到手机")
                        }
                        BluetoothClass.Device.Major.COMPUTER -> {
                            Log.d(TAG, "扫描到电脑")
                        }
                        BluetoothClass.Device.Major.TOY -> {
                            Log.d(TAG, "扫描到玩具")
                        }
                        BluetoothClass.Device.Major.PERIPHERAL -> {
                            Log.d(TAG, "扫描到外设")

                            peripheralDevices.add(device)
                        }
                        BluetoothClass.Device.Major.HEALTH -> {
                            Log.d(TAG, "扫描到健康设备")
                        }
                        BluetoothClass.Device.Major.AUDIO_VIDEO -> {
                            Log.d(TAG, "扫描到音频/视频设备")
                        }
                        else -> {
                            Log.d(TAG, "扫描到其他设备")
                        }
                    }

                    Log.d(TAG, "${device?.name}")
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
                Log.d(TAG, "蓝牙扫描结束")

                if (!bluetoothPairing) {
                    if (peripheralDevices.isNotEmpty()) {
                        handler.removeMessages(WHAT_BLUETOOTH_BOND)
                        handler.sendEmptyMessageDelayed(WHAT_BLUETOOTH_BOND, 5000)

                        textView.text = "扫描到外设"
                    } else {
                        Log.d(TAG, "没有扫描到外设")
                        handler.sendEmptyMessageDelayed(WHAT_BLUETOOTH_START_SCAN, 10000)

                        textView.text = "没有扫描到外设"
                    }
                }
            } else if (BluetoothDevice.ACTION_NAME_CHANGED == action) {
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                Log.d(TAG, "设备名称已改变：${device?.name}")
            }
        }
    }

    private lateinit var bluetoothAdapter: BluetoothAdapter

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: android.os.Message) {
            super.handleMessage(msg)
            when (msg.what) {
                WHAT_BLUETOOTH_START_SCAN -> {
                    Log.d(TAG, "开始扫描蓝牙设备")
                    startDiscovery()
                }
                WHAT_BLUETOOTH_BOND -> {

                    Log.d(TAG, "开始配对蓝牙设备")
                    bluetoothPairing = true
                    peripheralDevices.first().createBond()

                    textView.text = "开始配对蓝牙设备"

                    // 方法2：调用反射方法自动确认配对（适用于SSP配对）
//                    val setPairingConfirmationMethod =
//                        BluetoothDevice::class.java.getMethod(
//                            "setPairingConfirmation",
//                            Boolean::class.javaPrimitiveType
//                        )
//                    setPairingConfirmationMethod.invoke(peripheralDevices.first(), true) // 自动确认配对码

                }
            }
        }
    }

    //这里只收集外设
    private val peripheralDevices = mutableSetOf<BluetoothDevice>()

    private val bluetoothPairingReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent!!.action

            // 监听配对状态变化广播
            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED == action) {
                // 获取目标设备
                val device: BluetoothDevice =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) ?: return

                // 获取新状态和旧状态
                val newBondState =
                    intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)
                val oldBondState = intent.getIntExtra(
                    BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE,
                    BluetoothDevice.ERROR
                )

                // 判断配对结果
                if (newBondState == BluetoothDevice.BOND_BONDED) {
                    // 配对成功
                    Log.d(TAG, "配对成功")

                    textView.text = "配对成功，可以使用了"
                    bluetoothPairing = false
                } else if (newBondState == BluetoothDevice.BOND_NONE && oldBondState == BluetoothDevice.BOND_BONDING) {
                    // 配对失败或被取消（从“正在配对”变为“未配对”）
                    Log.d(TAG, "配对失败")
                    textView.text = "配对失败"
                    handler.removeMessages(WHAT_BLUETOOTH_START_SCAN)
                    handler.sendEmptyMessageDelayed(WHAT_BLUETOOTH_START_SCAN, 5000)
                    bluetoothPairing = false
                }
            }
        }
    }

    private val textView: TextView by lazy { findViewById(R.id.text_view) }

    private var bluetoothPairing = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//        textView.text = "欢迎使用蓝牙自动配对"

        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter

        val intentFilter3 = IntentFilter()
        intentFilter3.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        registerReceiver(bluetoothPairingReceiver, intentFilter3)
    }

    override fun onStart() {
        super.onStart()

        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(bluetoothStateReceiver, intentFilter)

        val intentFilter2 = IntentFilter()
        intentFilter2.addAction(BluetoothDevice.ACTION_FOUND)
        intentFilter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        intentFilter2.addAction(BluetoothDevice.ACTION_NAME_CHANGED)
        registerReceiver(bluetoothScanReceiver, intentFilter2)

        if (bluetoothAdapter.isEnabled) {
            Log.d(TAG, "Bluetooth is enabled")

            startDiscovery()
        } else {
            Log.d(TAG, "Bluetooth is not enabled")
            bluetoothAdapter.enable()
        }
    }

    private fun startDiscovery() {
        var needRequest = false
        permissions.forEach {
            if (ContextCompat.checkSelfPermission(
                    this,
                    it
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                needRequest = true
            }
        }

        if (needRequest) {
            ActivityCompat.requestPermissions(
                this,
                permissions,
                permissionRequestCode
            )
        } else {
            var ret = false
            bluetoothAdapter.bondedDevices.forEach {

                when (it.bluetoothClass.majorDeviceClass) {
                    BluetoothClass.Device.Major.PERIPHERAL -> {
                        Log.d(TAG, "已配对外设：${it?.name} $it")
                        if (isBluetoothInputInUse(it)) {
                            ret = true
                        }
                    }
                }
            }

            if (ret) {
                textView.text = "设备已正常使用"
                LocalBroadcastManager.getInstance(this).sendBroadcast(Intent(ACT_CLOSE_AUTO))
                return
            }

            if (bluetoothAdapter.isDiscovering) {
                bluetoothAdapter.cancelDiscovery()
            }
            bluetoothAdapter.startDiscovery()

            textView.text = "正在扫描蓝牙设备"
        }

    }

    override fun onStop() {
        super.onStop()

        handler.removeMessages(WHAT_BLUETOOTH_START_SCAN)
        unregisterReceiver(bluetoothStateReceiver)
        unregisterReceiver(bluetoothScanReceiver)

    }

    override fun onDestroy() {
        super.onDestroy()

        handler.removeCallbacksAndMessages(null)
        unregisterReceiver(bluetoothPairingReceiver)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == permissionRequestCode) {
            startDiscovery()
        }
    }

    /**
     * 检查蓝牙输入设备（键盘、鼠标）是否正在使用
     */
    fun isBluetoothInputInUse(device: BluetoothDevice): Boolean {

        val inputManager = getSystemService(INPUT_SERVICE) as InputManager
        val deviceIds = inputManager.inputDeviceIds
        for (deviceId in deviceIds) {
            val inputDevice = inputManager.getInputDevice(deviceId) ?: continue

            Log.d(TAG, "$inputDevice")

            if (inputDevice.name.contains(device.name)) {
                return true
            }
        }
        return false
    }

}